package com.detector.overflow;

import com.detector.overflow.config.DetectorConfig;
import org.objectweb.asm.*;
import java.lang.instrument.ClassFileTransformer;
import java.security.ProtectionDomain;

/**
 * 字节码转换器 - 监控数值运算
 *
 * @author detector
 */
public class OverflowTransformer implements ClassFileTransformer {
    
    private final DetectorConfig config = DetectorConfig.getInstance();
    
    @Override
    public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined,
                          ProtectionDomain protectionDomain, byte[] classfileBuffer) {
        
        // 使用配置判断是否监控
        if (!config.shouldMonitor(className)) {
            return null;
        }
        
        // 排除代理类和Lambda表达式
        if (className.contains("$$") || className.contains("$Lambda$")) {
            return null;
        }
        
        try {
            ClassReader cr = new ClassReader(classfileBuffer);
            ClassWriter cw = new ClassWriter(cr, ClassWriter.COMPUTE_MAXS);
            ClassVisitor cv = new OverflowClassVisitor(Opcodes.ASM9, cw, className);
            cr.accept(cv, ClassReader.EXPAND_FRAMES);
            return cw.toByteArray();
        } catch (Exception e) {
            // 转换失败不影响原类加载
            return null;
        }
    }
}
